<template>
  <p>count = {{ count }}</p>
  <p>
    <button @click="handleCount">点击+1</button>
  </p>
</template>

<script>
import {
  ref,
  onBeforeMount,
  onMounted,
  onBeforeUpdate,
  onUpdated,
  onBeforeUnmount,
  onUnmounted
} from 'vue'

export default {
  name: "Demo",
  setup() {

    const count = ref(0)

    const handleCount = () => {
      count.value += 1
    }

    // 定时器ID
    const timer = ref()

    // 启动定时器
    const startTimer = () => {
      console.log("==== 启动定时器 ====")
      timer.value = setInterval(() => {
        console.log("定时器执行")
        handleCount()

        // 如果累加到59以上，就销毁定时器
        if (count.value > 59) {
          clearTimer()
        }

      }, 1000)
    }

    // 销毁定时器
    const clearTimer = () => {
      if (timer.value) {
        console.log("==== 定时器销毁 ====")
        clearInterval(timer.value)
      }
    }

    onBeforeMount(() => {
      console.log('onBeforeMount 组件挂载之前');
    });

    onMounted(() => {
      console.log('onMounted 组件挂载完成');
      // 启动定时器
      startTimer()
    });

    onBeforeUpdate(() => {
      console.log('onBeforeUpdate 组件更新之前');
    });

    onUpdated(() => {
      console.log('onUpdated 组件更新完成');
    });

    onBeforeUnmount(() => {
      console.log('onBeforeUnmount 组件卸载之前');
      // 卸载定时器
      clearTimer()
    });

    onUnmounted(() => {
      console.log('onUnmounted 组件卸载完成');
    });

    return {
      count,
      handleCount
    }
  }
}
</script>

<style scoped>

</style>